package cn.icesun.comall.cybershoptest.module.user.controller;

import cn.icesun.comall.cybershoptest.module.user.dto.UserSaveDto;
import cn.icesun.comall.cybershoptest.module.user.dto.UserUpdatePasswordDto;
import cn.icesun.comall.cybershoptest.module.user.entity.User;
import cn.icesun.comall.cybershoptest.module.user.service.IUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/base/admin/users")
@Api(value = "用户管理端Api", tags = {"管理端-用户管理"})
public class UserAdminController {

    @Autowired
    private IUserService userService;


    @GetMapping("/search")
    @ApiOperation(value = "用户账户模糊查询分页")
    public IPage<User> findAllByLikeAccount(@RequestParam(value = "userAccount", defaultValue = "") String userAccount, @RequestParam("page") Integer page, @RequestParam("prePage") Integer prePage, HttpServletResponse response) {
        IPage<User> users = userService.page(new Page<>(page, prePage), Wrappers.<User>lambdaQuery().like(User::getUserAccount, "%" + userAccount + "%"));
        response.setStatus(HttpServletResponse.SC_OK);
        return users;
    }


    @GetMapping("/{id}")
    @ApiOperation(value = "用户详情")
    public User get(@PathVariable("id") @ApiParam("用户ID") Integer id, HttpServletResponse response) {
        User user = userService.getById(id);

        // 判断资源是否存在
        if (user == null){
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


        response.setStatus(HttpServletResponse.SC_OK);
        return user;
    }

    @PostMapping("/")
    @ApiOperation("新增用户")
    public User save(UserSaveDto userSaveDto, HttpServletResponse response){

        // 判断传入参数是否正常
        if (userSaveDto == null || userSaveDto.getUserAccount() == null || userSaveDto.getUserPassword() == null) {
            try {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        // 判断是否存在同名用户冲突
        Long existUserCount = userService.count(Wrappers.<User>lambdaQuery().eq(User::getUserAccount, userSaveDto.getUserAccount()));

        if (existUserCount > 0){
            try {
                response.sendError(HttpServletResponse.SC_CONFLICT, "用户名已存在");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        User user = new User();
        BeanUtils.copyProperties(userSaveDto, user);

        // 设置随机盐和密码摘要
        user.setUserSalt(UUID.randomUUID().toString().replace("-", ""));
        user.setUserPassword(
                DigestUtils.md5DigestAsHex(
                        (user.getUserSalt() + user.getUserPassword()).getBytes(StandardCharsets.UTF_8)));

        if (userService.save(user)){
            response.setStatus(HttpServletResponse.SC_CREATED);
            return user;
        }
        else {
            try {
                response.sendError(HttpServletResponse.SC_CONFLICT, "未知原因");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


    @PutMapping("/{id}/password")
    @ApiOperation("修改用户密码")
    public User updateUserPassword(
            @PathVariable("id")Integer id,
            @RequestBody UserUpdatePasswordDto userUpdatePasswordDto,
            HttpServletResponse response){
        User user = userService.getById(id);

        // 资源不存在
        if (user == null){
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        user.setUserPassword(
                DigestUtils.md5DigestAsHex(
                        (user.getUserSalt() + userUpdatePasswordDto.getUserPassword()).getBytes(StandardCharsets.UTF_8)));

        if (userService.update(
                Wrappers
                        .<User>lambdaUpdate()
                        .set(User::getUserPassword, user.getUserPassword())
                        .eq(User::getId, user.getId()))) {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
            return user;
        }
        else {
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void delete(@PathVariable("id") Integer id, HttpServletResponse response){

        // 逻辑删除用户, 保证幂等性要求
        userService.removeById(id);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
